package application;

import java.io.IOException;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class ClientSocket {
	
	String SERVER_IP; 
	static int SERVER_PORT;
	private static SSLSocket socket;
	private static int connected;
	private static int sockType;

	public ClientSocket(int sockType) {
		SERVER_IP = null;
		SERVER_PORT = (Integer) null;
		socket = null;
		sockType = -1;
		createSocket(sockType);
	}

	// Default constructor
	public void ClientSocket() 
	{
		SERVER_IP = null;
		SERVER_PORT = (Integer) null;
		socket = null;
		sockType = -1;
	}
	
	// Check whether a socket is connected
	public static int isConnected()
	{
		if(socket.isConnected()) {
			return 1;
		}
		else
			return 0;
	}
	
	// This method is used to create a socket of the given type
	public int createSocket(int type)
	{
		// byte[] returnCode = new byte[UserAccountConsts.USERACCOUNT_MAX_RES_LEN];
		switch(type) {
			
			case 1: SERVER_PORT = ClientConsts.SERVER_PORT_USER_ACCOUNT;
					break;
			case 2: SERVER_PORT = ClientConsts.SERVER_PORT_STATS;
					break;
			case 3: SERVER_PORT = ClientConsts.SERVER_PORT_GAME;
					break;
			default: SERVER_PORT = -9000;
					break;
		}
		try {
			SSLSocketFactory sslsocketfactory = ClientConsts.createSSLFactory();
			socket = (SSLSocket) sslsocketfactory.createSocket(
						ClientConsts.SERVER_IP, SERVER_PORT);
			connected = 1;
			
		} catch (Exception exception) {
			exception.printStackTrace();
			System.out.println("PreGameScreenFetchData::createSocket - Failed to create socket");
			connected = 0;
		}
		return connected;
	}
	
	// Call this function to close a socket
    public static int closeSocket()
    {
            int ret = 0;
            try {
            	socket.close();
            } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            }
            if(socket.isClosed()) {
                    ret = 1;
            }
            
            return ret;
    }
}
